package com.newfiber.business.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.newfiber.business.constant.BusinessConstants;
import com.newfiber.business.domain.PatrolCase;
import com.newfiber.business.domain.request.patrolCase.PatrolCaseQueryRequest;
import com.newfiber.business.domain.response.patrolExamine.*;
import com.newfiber.business.enums.EPatrolType;
import com.newfiber.business.mapper.PatrolCaseMapper;
import com.newfiber.business.mapper.PatrolTaskMapper;
import com.newfiber.common.core.exception.ServiceException;
import com.newfiber.common.core.utils.StringUtils;
import com.newfiber.common.core.web.service.BaseServiceImpl;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.newfiber.utils.OfficeUtil;
import com.newfiber.utils.WordBaseService;
import org.springframework.stereotype.Service;
import com.newfiber.business.mapper.PatrolExamineMapper;
import com.newfiber.business.domain.PatrolExamine;
import com.newfiber.business.domain.request.patrolExamine.PatrolExamineQueryRequest;
import com.newfiber.business.service.IPatrolExamineService;

import static cn.hutool.core.date.DatePattern.CHINESE_DATE_PATTERN;
import static com.newfiber.business.constant.BusinessConstants.EXAMINE_EXPORT_FILE_NAME;
import static com.newfiber.business.constant.BusinessConstants.EXAMINE_EXPORT_TEMPLATE;

/**
 * 巡查考核Service业务层处理
 *
 * @author lufan
 * @date 2023-03-03
 */
@Service
public class PatrolExamineServiceImpl extends BaseServiceImpl<PatrolExamineMapper, PatrolExamine> implements IPatrolExamineService {

    @Resource
    private PatrolExamineMapper patrolExamineMapper;

    @Resource
    private PatrolCaseMapper patrolCaseMapper;

    @Resource
    private PatrolTaskMapper PatrolCaseMapper;

    @Override
    public boolean insertBatch(List<PatrolExamine> patrolExamine) {
        return saveBatch(patrolExamine, patrolExamine.size());
    }

    @Override
    public PatrolExamine selectDetail(Long id) {
        PatrolExamine patPatrolExamine = patrolExamineMapper.selectById(id);
        if (null == patPatrolExamine) {
            throw new ServiceException(String.format("%s ID=%s 的记录不存在", this.getClass().getSimpleName(), id));
        }
        return patPatrolExamine;
    }

    @Override
    public List<PatrolExamineQueryResult> selectPage(PatrolExamineQueryRequest request) {
        return patrolExamineMapper.selectByCondition(request);
    }

    @Override
    public List<PatrolExamineQueryResult> selectList(PatrolExamineQueryRequest request) {
        return patrolExamineMapper.selectByCondition(request);
    }

    @Override
    public List<PatrolExamine> queryPatrolExamine(PatrolExamineQueryRequest patrolExamineQueryRequest) {
        return patrolExamineMapper.queryPatrolExamine(patrolExamineQueryRequest);
    }

    @Override
    public void beginExamine() {
        // 判断系统当前日期是不是 一个星期/一个月/一年 的第一天
        Date date = new Date();
        PatrolExamineQueryRequest patrolExamineQueryRequest = new PatrolExamineQueryRequest();
        if (2 == DateUtil.dayOfWeek(date)) {
            // 上个星期一
            patrolExamineQueryRequest.setStartDate(DateUtil.lastWeek());
            // 上个星期最后一天 也就是昨天
            patrolExamineQueryRequest.setEndDate(DateUtil.yesterday());
            queryExamineAndSave(patrolExamineQueryRequest, BusinessConstants.WEEK);
        }
        if (1 == DateUtil.dayOfMonth(date)) {
            // 上个月1号
            patrolExamineQueryRequest.setStartDate(DateUtil.lastMonth());
            // 上个月最后一天 也就是昨天
            patrolExamineQueryRequest.setEndDate(DateUtil.yesterday());
            queryExamineAndSave(patrolExamineQueryRequest, BusinessConstants.MONTH);
        }
        if (1 == DateUtil.dayOfYear(date)) {
            // 去年1号
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(Calendar.YEAR, -1);
            patrolExamineQueryRequest.setStartDate(calendar.getTime());
            // 去年最后一天 也就是昨天
            patrolExamineQueryRequest.setEndDate(DateUtil.yesterday());
            queryExamineAndSave(patrolExamineQueryRequest, BusinessConstants.YEAR);
        }
    }

    private void queryExamineAndSave(PatrolExamineQueryRequest patrolExamineQueryRequest, String unit) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DatePattern.NORM_DATE_PATTERN);
        // 扫描pat_patrol_task和pat_patrol_log里面的数据
        List<PatrolExamine> patrolExamines = queryPatrolExamine(patrolExamineQueryRequest);

        // 插入数据到pat_patrol_examine表
        if (!patrolExamines.isEmpty()) {
            patrolExamines.forEach(e -> {
                e.setExamineRange(simpleDateFormat.format(patrolExamineQueryRequest.getStartDate())
                        + "--" + simpleDateFormat.format(patrolExamineQueryRequest.getEndDate()));
                e.setExamineUnit(unit);
            });
            insertBatch(patrolExamines);
        }
    }

    @Override
    public void export(HttpServletResponse response, PatrolExamineQueryRequest patrolExamine) {
        // 准备数据
        PatrolExamineExport patrolExamineExport = PatrolCaseMapper.examineCount(patrolExamine);
        patrolExamineExport.setTitle("厂网河");
        SimpleDateFormat sdf = new SimpleDateFormat(CHINESE_DATE_PATTERN);
        patrolExamineExport.setDate(sdf.format(patrolExamine.getStartDate()) + "-" + sdf.format(patrolExamine.getEndDate()));

        List<String> riverCaseType = patrolCaseMapper.caseTypeCount(EPatrolType.River.getCode(), patrolExamine);
        patrolExamineExport.setRiverCaseReportMainCaseType(StringUtils.join(riverCaseType, ","));
        List<String> pipelineCaseType = patrolCaseMapper.caseTypeCount(EPatrolType.Pipeline.getCode(), patrolExamine);
        patrolExamineExport.setPipelineCaseReportMainCaseType(StringUtils.join(pipelineCaseType, ","));

        List<PatrolCaseSource> riverCaseSource = patrolCaseMapper.caseSourceCount(EPatrolType.River.getCode(), patrolExamine);
        patrolExamineExport.setPatrolRiverCaseSourceStr(getCaseAndCount(riverCaseSource));
        patrolExamineExport.setRiverCaseReceived(String.valueOf(riverCaseSource.stream().mapToInt(PatrolCaseSource::getTotal).sum()));
        List<PatrolCaseSource> patrolCaseSource = patrolCaseMapper.caseSourceCount(EPatrolType.Pipeline.getCode(), patrolExamine);
        patrolExamineExport.setPatrolPipelineCaseSourceStr(getCaseAndCount(patrolCaseSource));
        patrolExamineExport.setPipelineCaseReceived(String.valueOf(patrolCaseSource.stream().mapToInt(PatrolCaseSource::getTotal).sum()));

        List<PatrolCaseFinish> riverCaseFinish = patrolCaseMapper.patrolTargetCaseCount(EPatrolType.River.getCode(), patrolExamine);
        patrolExamineExport.setPatrolRiverCaseFinishStr(getPatrolCaseAndCount(riverCaseFinish));
        List<PatrolCaseUnFinish> patrolCaseUnFinish = patrolCaseMapper.patrolTargetUnFinishCaseCount(EPatrolType.Pipeline.getCode(), patrolExamine);
        patrolExamineExport.setPatrolPipelineCaseUnFinishStr(getPatrolUnFinishCaseAndCount(patrolCaseUnFinish));

        List<List<String>> tableData = new ArrayList<>();
        // 表数据
        PatrolCaseQueryRequest request = new PatrolCaseQueryRequest();
        request.setPatrolType(EPatrolType.Pipeline.getCode());
        if (null != patrolExamine.getStartDate() && null != patrolExamine.getEndDate()) {
            request.setStartDate(patrolExamine.getStartDate());
            request.setEndDate(patrolExamine.getEndDate());
        }
        List<PatrolCase> patrolCaseList = patrolCaseMapper.selectByCondition(request);
        AtomicInteger i = new AtomicInteger(1);
        patrolCaseList.forEach(e -> {
            List<String> patrolCaseStr = new ArrayList<>();
            patrolCaseStr.add(String.valueOf(i.getAndIncrement()));
            patrolCaseStr.add(e.getCaseTypeStr());
            patrolCaseStr.add(e.getPatrolSectionName());
            patrolCaseStr.add(e.getCaseContent());
            tableData.add(patrolCaseStr);
        });

        patrolExamineExport.setTableData(tableData);
        try {
            WordBaseService wordBaseService = new WordBaseService();
            byte[] bytes = wordBaseService.toWordList(patrolExamineExport, EXAMINE_EXPORT_TEMPLATE);
            if (bytes != null) {
                OfficeUtil.exportByteStreamToClient(response, bytes, EXAMINE_EXPORT_FILE_NAME);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private String getCaseAndCount(List<PatrolCaseSource> caseSource) {
        StringBuffer sb = new StringBuffer();
        caseSource.forEach(e -> {
            sb.append(e.getCaseSource() + e.getTotal() + "个，已完成" + e.getEndCount() + "个。");
        });
        return sb.toString();
    }

    private String getPatrolCaseAndCount(List<PatrolCaseFinish> caseFinishes) {
        StringBuffer sb = new StringBuffer();
        caseFinishes.forEach(e -> {
            sb.append(" 涉及" + e.getPatrolTarget() + e.getCaseCount() + "个，已完成" + e.getCaseCountDone() + "个。\r\n");
        });
        return sb.toString();
    }

    private String getPatrolUnFinishCaseAndCount(List<PatrolCaseUnFinish> patrolCaseUnFinishes) {
        StringBuffer sb = new StringBuffer();
        patrolCaseUnFinishes.forEach(e -> {
            sb.append("   " + e.getCaseType() + "问题" + e.getCaseCount() + "个，未完成" + e.getCaseCountUnDone() + "个。\r\n");
        });
        return sb.toString();
    }
}
